<template>
	<view class="">

		<view class="container" id="contractimage" :style="{'backgroundColor': currentColor.hex}">
			<view class="poetry"
				:style="{'backgroundColor': `rgba(${currentColor.RGB[0]}, ${currentColor.RGB[1]}, ${currentColor.RGB[2]}, 0.5)`, 'color': `${oppositeColor}`}">
				<view class="line">{{poetry.content[0]}}</view>
				<view class="line">{{poetry.content[1]}}</view>
				<text class="poetry-title">{{poetry.author}} · {{poetry.title}}</text>
			</view>
			<view class="name" :style="{'color': oppositeColor}">{{currentColor.name}}</view>
			<image v-if="currentColor.figure"
				:style="{'height': `${figureHeight}`,'width': `${figureW}`,'opacity': `${figureO}`}"
				style="position: absolute;bottom: 0;" class="figure"
				:src="'https://colors.ichuantong.cn/figure/' +currentColor.figure" @load="handleFigureLoad">
			</image>
			<image v-else class="figure default-figure" src="https://colors.ichuantong.cn/figure/default.png"></image>
		</view>
		<view class="generate-image-button" @click="saveBase64ImgFile">生成图片</view>
	</view>
</template>

<script>
	const COLORS = require('../../utils/data.js')
	const {
		getCorrectTextColor
	} = require('../../utils/util.js')

	export default {
		data() {
			return {
				currentColor: {
					RGB: []
				},
				poetry: {},
				oppositeColor: '',
				canvasImage: '',
				figureHeight: 'auto',
				figureW: 'auto',
				figureO: 1,
			}
		},
		onLoad(options) {
			const id = options.id.split('-')
			const currentColorSet = COLORS.find(item => item.id === Number(id[0]))
			const currentColor = currentColorSet.colors[id[1]]
			this.poetry = JSON.parse(options.poetry)
			this.currentColor = currentColor
			this.oppositeColor = getCorrectTextColor(currentColor.RGB)
			console.log(this.poetry, this.currentColor, this.oppositeColor);
		},
		methods: {
			getParams(figure) {
				const search = {}
				const index = figure.indexOf('?')
				if (index === -1) return search
				figure.slice(index + 1).split('&').forEach((item) => {
					const kv = item.split('=')
					if (kv) {
						search[kv[0]] = kv[1]
					}
				})
				return search
			},
			handleFigureLoad: function(event) {
				const {
					height,
					width
				} = event.detail
				const {
					figure
				} = this.currentColor
				const params = this.getParams(figure)
				const figureW = params['width'] ? params['width'] === '100%' ? '750' : params['width'] * 28 : '644'
				const figureO = +(params['o'] || 1);
				this.figureHeight = `${figureW * height / width}rpx`
				this.figureW = figureW + 'rpx'
				this.figureO = figureO
			},

			showLoading() {
				uni.showLoading({
					title: '图片生成中…',
					mask: true
				})
			},
			hideLoading() {
				uni.hideLoading()
			},
			errorLoad(e) {
				console.log('图片加载失败：', e);
			},
			renderFinish(opt) { //截图成功回调
				console.log('opt', opt);
				let img = opt.path
				this.img = img;
				this.width = opt.width;
				this.height = opt.height;

				//格式化base64
				let base64 = img.replace(/^data:image\/\w+;base64,/, "");
				this.base64Img = base64 //保存base64字符串

				// this.saveBase64ImgFile();	//将base64文件保存到相册
			},
			saveBase64ImgFile() { //将base64文件保存到本地相册
				this.showLoading()
				let t = this;
				let base64 = t.base64Img
				console.log(base64);
				//手机端将base64转成png图片，此处需要使用真机调试
				const bitmap = new plus.nativeObj.Bitmap('text');
				bitmap.loadBase64Data(base64, function() {
					const url = "_doc/" + new Date().getTime() + ".png"; // url为时间戳命名方式
					console.log("saveBase64ImgFile", url)
					bitmap.save(url, {
						overwrite: true
					}, (i) => {
						console.log(1, i);

						uni.saveImageToPhotosAlbum({
							filePath: i.target,
							success() {
								console.log('图片保存成功')
								uni.showToast({
									title: '保存成功',
									icon: 'none'
								})
								bitmap.clear()
							}
						})
					}, e => {
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						})
						console.log('e==>', e);
						bitmap.clear()
					})
				}, (e) => {
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					})
					bitmap.clear()
				})
			},




			async handleGenerateImage() {
				await this.getSetting()
				wx.showLoading({
					title: '图片生成中',
					mask: true,
				})
				if (this.data.canvasImage) {
					this.extraImage()
					return
				}
				try {
					const canvas = await this.drawCanvas()
					const res = await this.canvasToTempFilePath(canvas)
					this.setData({
						canvasImage: res.tempFilePath
					}, () => {
						this.extraImage()
					})
				} catch (e) {
					wx.hideLoading()
					wx.showToast({
						title: '图片生成失败',
						icon: 'none',
					})
				}
			},
			extraImage() {
				wx.saveImageToPhotosAlbum({
					filePath: this.data.canvasImage,
					success(res) {
						wx.showToast({
							title: '图片已保存',
							icon: 'success',
						})
					},
					fail: (error) => {
						if (error.errMsg && error.errMsg.includes('cancel')) return
						if (error.errMsg.includes('fail auth deny')) {
							wx.showModal({
								title: '保存失败',
								content: '请允许保存到相册',
								success(res) {
									if (res.confirm) {
										wx.openSetting()
									}
								},
								complete: () => {
									this.setData({
										canvasImage: ''
									})
								}
							})
							return
						}
						wx.showToast({
							title: error.errMsg || '图片保存失败',
							icon: 'none',
						})
					},
					complete() {
						wx.hideLoading()
					}
				})
			},
			getCanvas() {
				return new Promise((resolve) => {
					const query = wx.createSelectorQuery()
					query.select('#PREVIEW_CANVAS')
						.fields({
							node: true,
							size: true
						})
						.exec((res) => {
							resolve(res[0])
						})
				})
			},
			async drawCanvas() {
				const {
					width,
					height,
					node
				} = await this.getCanvas()
				const canvas = node
				const ctx = canvas.getContext('2d')
				const systemInfo = wx.getSystemInfoSync()
				const dpr = systemInfo.pixelRatio
				console.log(systemInfo)
				canvas.width = width * dpr
				canvas.height = height * dpr
				ctx.scale(dpr, dpr)

				const {
					oppositeColor,
					currentColor,
					poetry
				} = this.data

				ctx.fillStyle = currentColor.hex
				ctx.fillRect(0, 0, width, height)

				await this.drawImage(canvas, ctx)

				ctx.font = 'normal bold 16px TChinese'
				ctx.textBaseline = 'bottom'
				ctx.fillStyle = oppositeColor
				ctx.fillText(currentColor.name, 10, height - 20)

				ctx.font = 'normal bold 22.4px cursive'
				const metrics1 = ctx.measureText(poetry.content[0])
				const metrics2 = ctx.measureText(poetry.content[1])
				ctx.font = 'normal 11.2px cursive'
				const metrics3 = ctx.measureText(`${poetry.author} · ${poetry.title}`)
				const minWidth = 84 * width / 375
				const maxWidth = Math.max(metrics1.width, metrics2.width, metrics3.width, minWidth)
				ctx.font = 'normal bold 22.4px cursive'
				ctx.fillText(poetry.content[0], (width - maxWidth) / 2, 146 * width / 375)
				ctx.fillText(poetry.content[1], (width - maxWidth) / 2, 146 * width / 375 + 35.84)
				ctx.font = 'normal 11.2px cursive'
				ctx.fillText(`${poetry.author} · ${poetry.title}`, (width - maxWidth) / 2, 146 * width / 375 + 71.68)
				return canvas
			},
			canvasToTempFilePath(canvas) {
				return new Promise((resolve, reject) => {
					wx.canvasToTempFilePath({
						canvas,
						success: (res) => {
							resolve(res)
						},
						fail(error) {
							reject(error)
						}
					})
				})
			},
			drawImage(canvas, ctx) {
				return new Promise((resolve, reject) => {
					const {
						currentColor,
						pos,
						figureO
					} = this.data
					const figureImg = canvas.createImage();
					figureImg.src =
						`https://colors.ichuantong.cn/figure/${currentColor.figure || 'default.png'}`; //微信请求返回头像
					const params = this.getParams(currentColor.figure || 'default.png?width=8')
					const dpr = wx.getSystemInfoSync().pixelRatio
					const figureW = params['width'] ? (params['width'] === '100%' ? canvas.width / dpr : params[
						'width'] * 14 * canvas.width / dpr / 375) : 322 * canvas.width / dpr / 375
					figureImg.onload = () => {
						const {
							width,
							height
						} = figureImg
						let dHeight = figureW * height / width
						let dy = pos === 'top' ? 0 : canvas.height / dpr - dHeight
						let dx = canvas.width / dpr - figureW
						if (pos === 'left') {
							dx = 0
							dy = 0
						}
						console.log(dx, dy, figureW, dHeight)
						ctx.save();
						ctx.globalAlpha = 0.8
						ctx.drawImage(figureImg, dx, dy, figureW, dHeight)
						ctx.restore()
						resolve()
					}
					figureImg.onerror = (error) => {
						reject(error)
					}
				})
			},
			getSetting() {
				return new Promise((resolve, reject) => {
					wx.getSetting({
						success(res) {
							if (res.authSetting['scope.writePhotosAlbum'] === false) {
								wx.showModal({
									content: '未授权相册，请先授权相册',
									success(res) {
										if (res.confirm) {
											wx.openSetting()
										}
									}
								})
								reject()
							} else {
								resolve()
							}
						},
						fail() {
							resolve()
						}
					})
				})
			},
		}
	}
</script>

<script module="html2canvas" lang="renderjs">
	import html2canvas from 'html2canvas';
	export default {
		mounted() { //注意：当前页面渲染完成后，则会开始生成图片
			let that = this;
			setTimeout(() => {
				that.emitData()
			}, 300)
		},
		methods: {
			emitData() {
				// 根据自己需要截图区域
				console.log("开始生成图片");
				this.create('contractimage');
			},
			async create(id) {
				if (!id) {
					return false;
				}
				try {
					// this.$ownerInstance.callMethod('showLoading', true);
					const timeout = setTimeout(async () => {
						const domId = document.getElementById(id);
						const canvas = await html2canvas(domId, {
							width: domId.offsetWidth, //设置canvas尺寸与所截图尺寸相同，防止白边
							height: domId.offsetHeight, //防止白边
							logging: true,
							useCORS: true
						});

						const base64 = canvas.toDataURL('image/jpeg', 1);
						//base64图片生成成功后，执行renderFinish将base64传回去
						this.$ownerInstance.callMethod('renderFinish', {
							path: base64,
							el: id,
							height: domId.offsetHeight,
							width: domId.offsetWidth
						});
						clearTimeout(timeout);
						this.$ownerInstance.callMethod('hideLoading', true);
					}, 500);
				} catch (error) {
					this.$ownerInstance.callMethod('hideLoading', true);
					console.log(error)
				}
			}
		}
	}
</script>


<style>
	.container {
		font-variant: normal;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		top: 0;
		z-index: 999;
		background-image: url(https://m.ifable.cn/images/bg.png);
		background-repeat: repeat;
		width: 100vw;
		color: rgb(255, 255, 235);
	}

	.poetry {
		position: absolute;
		left: 50%;
		top: 252rpx;
		transform: translateX(-50%);
		min-width: 168rpx;
		white-space: nowrap;
		line-height: 1.6;
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		padding: 22.4rpx 33.6rpx;
	}

	.poetry .line {
		font-size: 44.8rpx;
		font-weight: bold;
		word-break: keep-all;
		color: inherit;
		font-family: inherit;
		letter-spacing: 2px;
	}

	.poetry-title {
		font-size: 22.4rpx;
		word-break: keep-all;
		margin-top: 28rpx;
		color: inherit;
		font-family: inherit;
	}

	.name {
		position: absolute;
		left: 0;
		bottom: 0;
		margin-left: 28rpx;
		margin-bottom: 28rpx;
		font-family: TChinese, serif;
		z-index: 99;
	}

	.figure {
		position: absolute;
		right: 0;
		z-index: -1;
		max-height: 100%;
	}

	.default-figure {
		width: 224rpx;
		height: 283.12rpx;
		bottom: 0;
	}

	.generate-image-button {
		position: absolute;
		left: 50%;
		bottom: 10vh;
		transform: translateX(-50%);
		border: none;
		border-radius: 8.4rpx;
		padding: 16.8rpx 22.4rpx;
		font-size: 28rpx;
		color: rgb(238, 238, 238);
		background: rgb(31, 47, 45);
		box-shadow: rgba(0, 0, 0, 0.5) 0 10rpx 18rpx;
		z-index: 999;
	}

	.preview-canvas {
		position: absolute;
		left: -100vw;
		height: 100vh;
		width: 100vw;
	}
</style>
